import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class HttpclientProvider {
    constructor(public http: HttpClient) {}
    GET(url: string, params: any, callback?: (res: any, error: any) => void): void {
        //Get方法
        this.http.get(url, { params: this.encodeComplexHttpParams(params) }).subscribe(
            (res) => {
                callback && callback(res, null);
            },
            (error) => {
                callback && callback(null, error);
            }
        );
    }
    POST(url: string, params: any, callback?: (res: any, error: any) => void): void {
        //POST方法
        this.http.post(url, { params: this.encodeComplexHttpParams(params) }).subscribe(
            (res) => {
                callback && callback(res, null);
            },
            (error) => {
                callback && callback(null, error);
            }
        );
    }

    private paramsString(params: any): string {
        if (!params) return null;
        let str = '';
        for (let key in params) {
            if (params.hasOwnProperty(key)) {
                //判断自身属性是否存在
                let value = params[key];
                if (value === null) continue;
                if (Array.isArray(value)) {
                    //数组
                    if (value.length === 0) continue;
                    for (let index = 0; index < value.length; index++) {
                        //数组拼接字符串
                        let k = key + '[' + index + ']';
                        let v = value[index];
                        if (str.length > 1) str += '&'; //填写连字符;
                        str += k + '=' + v;
                    }
                } else if (this.isObject(value)) {
                    for (let subKey in value) {
                        if (value.hasOwnProperty(subKey)) {
                            let v = value[subKey];
                            if (v === null) continue;
                            let k = key + '[' + subKey + ']';
                            if (str.length > 1) str += '&'; //填写连字符;
                            str += k + '=' + v;
                        }
                    }
                } else {
                    if (str.length > 1) str += '&'; //填写连字符;
                    str += key + '=' + value;
                }
            }
        }
        return str;
    }
    private encodeComplexHttpParams(params: any): any {
        if (!params) return null;
        return new HttpParams({ fromString: this.paramsString(params) });
    }
    private isObject(val) {
        //检测对象
        return val != null && typeof val === 'object' && Array.isArray(val) === false;
    }
}
